package com.example.fantacylib

import android.R.attr.height
import android.R.attr.width
import android.graphics.Bitmap
import android.os.Bundle
import android.os.CountDownTimer
import android.os.FileUtils
import android.util.Log
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.databinding.DataBindingUtil
import androidx.viewpager2.widget.ViewPager2
import com.bumptech.glide.Glide
import com.example.baseutils.BitmapUtil
import com.example.baseutils.FileUtil
import com.example.baseutils.activity.BaseLoadActivity
import com.example.baseutils.showToast
import com.example.baseutils.start
import com.example.fantacylib.databinding.ActivityPayBinding
import com.example.fantacylib.ui.BannerImage
import com.example.fantacylib.ui.ImageAdapter
import com.example.net.http.FantacyRetrofitCreator
import com.youth.banner.indicator.CircleIndicator
import com.youth.banner.listener.OnPageChangeListener
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.cancel
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext


/**
 * 付款页面
 * 2024年09月03日17:24:15
 * author:lp
 * 原型：https://js.design/f/1YrM5i?p=fyMYMso6FR&mode=design
 * */
class PayActivity : BaseLoadActivity() {
    private val TAG = "PayActivity"
    private lateinit var binding: ActivityPayBinding
    private val mAutoOutTime = 30
    private val bannerList = mutableListOf<BannerImage>()
    private var autoOutTimer: CountDownTimer? = null
    private var price=""
    private var payQr=""
    private val mainScope= CoroutineScope(Dispatchers.Main)
    private val payScope= CoroutineScope(Dispatchers.IO)
    private var payState=false
    private var orderId=0
    private var seletePath=""
    override fun onLoad() {
        //一直查询付款的状态
        payScope.launch {
            while (!payState){
                delay(1000)
                //请求付款二维码
                getQr()
                payState=FantacyRetrofitCreator.checkPay(orderId)
                Log.i(TAG, "payState: $payState  seletePath $seletePath")
            }
            val bitmap: Bitmap = Glide.with(this@PayActivity)
                .asBitmap()
                .load(seletePath)
                .override(1844,1240)
                .submit().get()
            CaptureActivity.localPath =FileUtil.getPicPath("fantacy_merge")
            Log.i(TAG, "localPath: ${CaptureActivity.localPath}")
            BitmapUtil.save2jpg(bitmap, CaptureActivity.localPath)
            withContext(Dispatchers.Main){
                WaitActivity().start(this@PayActivity)
            }
        }
    }
    private fun getQr():Boolean{
        if(payQr.isNotEmpty()){
            return false
        }
        mainScope.launch {
            val qrResult=FantacyRetrofitCreator.queryQr(orderId)
            if (qrResult==null){
                "付款二维码查询失败，请重试".showToast(this@PayActivity)
                return@launch
            }
            payQr=qrResult.payCodeUrl
            Glide.with(binding.ivQr).load(payQr).into(binding.ivQr)
        }
        return true
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_pay)
        binding.btnBack.setOnClickListener { finish() }
        binding.btnPrint.setOnClickListener {
            binding.bannerPay.isAutoLoop(false)
            visibleQr()
            autoOutTimer()
        }
        price=intent.getStringExtra(CaptureActivity.PRICE_KEY)?:"未获取到"
        orderId=intent.getIntExtra(CaptureActivity.ORDER_ID,0)
        binding.tvAmount.text=price+"元"
        val newList=intent.getStringArrayListExtra(CaptureActivity.MERGE_LIST)
        Log.i(TAG, "newList: $newList")
        seletePath=newList?.get(0)?:""
        if(!newList.isNullOrEmpty()){
            newList.forEach {
                bannerList.add(BannerImage(it))
            }
        }
        payBanner()
        autoOutTimer()
        binding.btnPrint.performClick()
    }

    override fun onStart() {
        super.onStart()
        autoOutTimer()
    }

    override fun onStop() {
        super.onStop()
        autoOutTimer?.cancel()
        mainScope.cancel()
        payScope.cancel()
    }

    private fun visibleQr() {
        //如果已经是隐藏，则启动显示
        if (binding.clPay.visibility == View.VISIBLE) {
            binding.clPay.visibility = View.GONE
            binding.ivArrow.rotation = 270f
        } else {
            getQr()
            binding.clPay.visibility = View.VISIBLE
            binding.ivArrow.rotation = 90f
        }
    }

    private fun payBanner() {
        binding.bannerPay.addBannerLifecycleObserver(this)
            .setAdapter(ImageAdapter(bannerList))
            .setIndicator(CircleIndicator(this))

        binding.bannerPay.setOnBannerListener { data, position ->
            Log.i(TAG, "onBannerClick: $data position:$position")
            //手动点击之后就不再自动轮播
            binding.bannerPay.isAutoLoop(false)
            autoOutTimer()
        }
        binding.bannerPay.addOnPageChangeListener(object : OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                Log.i(TAG, "onPageScrolled: ")
            }

            override fun onPageSelected(position: Int) {
                Log.i(TAG, "onPageSelected: $position  ${bannerList[position].imageUri}")
                seletePath=bannerList[position].imageUri

            }

            override fun onPageScrollStateChanged(state: Int) {
                if (state == ViewPager2.SCROLL_STATE_DRAGGING) {
                    autoOutTimer()
                    //手动滑动之后就不再自动轮播
                    binding.bannerPay.isAutoLoop(false)
                }
            }
        })
    }

    private fun autoOutTimer(force: Boolean = false) {
        autoOutTimer?.cancel()
        autoOutTimer = object : CountDownTimer(mAutoOutTime * 1000L, 1000L) {
            override fun onTick(p0: Long) {}
            override fun onFinish() {
                if (force) {
                    FantacyMain().start(this@PayActivity)
                    return
                }
                AlertDialog.Builder(this@PayActivity)
                    .setTitle("超时退出提示")
                    .setMessage("即将在 $mAutoOutTime 秒后自动退出到主页面！")
                    .setNegativeButton("稍等一会儿") { dialog, which ->
                        //重复超时计时
                        autoOutTimer()
                    }
                    .setPositiveButton("退出吧") { dialog, which -> finish() }.show()
                autoOutTimer(true)
            }
        }.start()
    }

    override fun onDestroy() {
        super.onDestroy()
        payScope.cancel()
        mainScope.cancel()
    }
}